﻿using System;
using System.Collections.Generic;

namespace TC
{
    /// <summary>
    /// 结果“与”
    /// </summary>
    public class Parallel : BTNode, IUpdate
    {
        public List<FlowOutput<FlowNode>> flows;
        public List<Dispatcher> calls;

        private List<int> callstatus = new List<int>();
        private int finalStatus = 0;

        public override void Execute(Dispatcher chain)
        {
            base.Execute(chain);

            for (int i = 0; i < flows.Count; ++i)
            {
                int index = i;
                calls[i].onComplete = (int status) => { OnComplete(index, status); };
                calls[i].Call(flows[i]);
            }
        }

        public override void Stop()
        {
            base.Stop();

            foreach (var i in calls)
            {
                i.Destroy();
            }
        }

        public void OnUpdate(float delta)
        {
            foreach (var i in calls)
            {
                i.Update(delta);
            }
        }

        //
        private void OnComplete(int index, int status)
        {
            callstatus[index] = status;
            if (status == 1)
                finalStatus = 1;

            foreach (var i in callstatus)
            {
                //2表示running
                if (i == 2)
                {
                    return;
                }
            }

            //当前Parallel节点结束
            chain.End(status);
        }
    }
}
